//
//  RegisterViewController.m
//  muscleLife
//
//  Created by xalo on 16/4/28.
//  Copyright © 2016年 HeavenAndHell. All rights reserved.
//

#import "RegisterViewController.h"

typedef enum{

    RegisterActionStateSuccess,
    RegisterActionStateFail,
}RegisterActionState;

@interface RegisterViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *usrNameText;
@property (weak, nonatomic) IBOutlet UITextField *passWord;
@property (weak, nonatomic) IBOutlet UITextField *eMailText;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UITextField *surePassword;

@property (assign, nonatomic)BOOL isChangeFrame;
@property (assign, nonatomic)RegisterActionState registerState;
@end

@implementation RegisterViewController

#pragma mark - 视图的生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTextField];
    [self registerNotifiation];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//监听键盘通知，改变页面的frame
- (void)registerNotifiation{

    //发送键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    //发送键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden:) name:UIKeyboardDidHideNotification object:nil];
}

-(void)keyboardDidShow:(NSNotification*)notification{

    if ([self.eMailText isFirstResponder]) {

        //获取键盘高度
        NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect;
        [keyboardObject getValue:&keyboardRect];

        //取得键盘动画时间，让屏幕的平移更加连贯
        double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //调整位置
        [UIView animateWithDuration:duration animations:^{

            [self.view setFrame:CGRectMake(0, -keyboardRect.size.height, kControllerWidth, kControllerHeight)];
            self.isChangeFrame = YES;
        } completion:^(BOOL finished) {

        }];
    }

}

-(void)keyboardDidHidden:(NSNotification*)notification{

    if (self.isChangeFrame == YES) {

        [UIView animateWithDuration:0.1 animations:^{

            [self.view setFrame:CGRectMake(0, 0, kControllerWidth, kControllerHeight)];
            self.isChangeFrame = NO;
        } completion:^(BOOL finished) {

        }];
    }

}
//设置文本输入框
-(void)setTextField{
//    self.usrNameText.borderStyle = UITextBorderStyleLine;
    [self.usrNameText addTarget:self action:@selector(usrNameTextAction:) forControlEvents:UIControlEventEditingDidEnd];
    self.passWord.secureTextEntry = YES;
    self.surePassword.secureTextEntry = YES;//密文输入
    self.passWord.clearsOnBeginEditing = YES;//再次输入时清空
    self.surePassword.clearsOnBeginEditing = YES;
    [self.surePassword addTarget:self action:@selector(passWordAction:) forControlEvents:UIControlEventEditingDidEnd];//目标方法用来检测两次输入是否一致；
    [self.passWord addTarget:self action:@selector(passWordAction:) forControlEvents:UIControlEventEditingDidEnd];
    self.registerBtn.userInteractionEnabled = NO;
    [self.registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.registerBtn setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
}

//检测用户名是否有重复的方法
-(void)usrNameTextAction:(UITextField*)sender{
#warning message - 还没点击注册按钮的时候就检测，是否重名
    NSLog(@"用户名输入完毕");
    if ([sender.text isEqualToString:@""]) {
        NSLog(@"用户名不能为空");
    }
}

//确认密码框的回调方法，判断两次输入密码是否一致
-(void)passWordAction:(UITextField*)sender{
    //检测是否和密码框一致
    NSLog(@"确认密码框输入完毕");
    if ([self.passWord.text isEqualToString:self.surePassword.text]) {
        NSLog(@"密码输入一致");
        self.registerBtn.userInteractionEnabled = YES;
    }else{
        NSLog(@"密码输入不一致");
    }

}

- (IBAction)registerBtn:(UIButton *)sender {

    
    AVUser *usr = [AVUser user];//新建用户
    usr.username = self.usrNameText.text;
    usr.password = self.passWord.text;
    usr.email = self.eMailText.text;
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在注册...";
    [usr signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            //注册成功
            NSLog(@"注册成功");
            self.registerState = RegisterActionStateSuccess;
            [hud hide:YES];
            [self presentAlertViewWithMessage:@"注册成功"];
        }else{
            [hud hide:YES];
            //注册失败
            self.registerState = RegisterActionStateFail;
        }
    }];
    
}

-(void)presentAlertViewWithMessage:(NSString*)message{

    UIAlertController* alertView = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* action = [UIAlertAction actionWithTitle:@"欢迎来到肌活" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        if (self.registerState == RegisterActionStateSuccess) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
    [alertView addAction:action];
    [self presentViewController:alertView animated:YES completion:^{

    }];
}

/**
 *  三个textFaild都使用了代理，用户代理用来判断是否有重复的用户名。密码代理用来判断是否密码输入一致
 *
 */
-(void)textFieldDidEndEditing:(UITextField *)textField{

    //确保每个注册的都不为空
    if (textField.text == nil||[textField.text isEqualToString:@""]) {
        self.registerBtn.userInteractionEnabled = NO;
        NSLog(@"输入为空，不能进行注册");
    }
    NSLog(@"结束了输入");
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{


    //释放键盘
    [textField resignFirstResponder];
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //释放键盘
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
